import React, { useEffect, useState } from "react";
import { Button, Table, Form, Input, DatePicker, Select, Modal } from "antd";
import { getadd, getdata } from "../../api";
const { Option } = Select;
import * as XLSX from "xlsx";
function MaterialDownload() {
  const columns = [
    {
      title: "序号",
      dataIndex: "serialNumber",
      key: "serialNumber",
    },
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "店铺名称",
      dataIndex: "shopName",
      key: "shopName",
    },
    {
      title: "手机号码",
      dataIndex: "phoneNumber",
      key: "phoneNumber",
    },
    {
      title: "业务单据",
      dataIndex: "businessDocument",
      key: "businessDocument",
    },
    {
      title: "业务类型",
      dataIndex: "businessType",
      key: "businessType",
    },
    {
      title: "流水类型",
      dataIndex: "transactionType",
      key: "transactionType",
    },
    {
      title: "时间",
      dataIndex: "date",
      key: "date",
    },
    {
      title: "果币",
      dataIndex: "amount",
      key: "amount",
      render: (text) => <span style={{ color: "red" }}>{text}</span>,
    },
  ];
  const [data, setdata] = useState([]);
  const [searchData, setsearchData] = useState([]); // 用于存储筛选后的数据
  const getList = async () => {
    const res = await getdata();
    console.log(res);
    setdata(res.data);
    setsearchData(res.data);
  };
  useEffect(() => {
    getList();
  }, []);
  const [form] = Form.useForm();
  const [formLayout, setFormLayout] = useState("inline");
  const onFinish = async (values) => {
    console.log("Received values of form: ", values);
    let newsearchData = data;
    // 根据业务类型筛选
    if (values.businessType) {
      newsearchData = newsearchData.filter(
        (item) => item.businessType === values.businessType
      );
    }
    // 根据店铺名称筛选
    if (values.shopName) {
      newsearchData = newsearchData.filter((item) =>
        item.shopName.includes(values.shopName)
      );
    }
    // 根据手机号码筛选
    if (values.phoneNumber) {
      newsearchData = newsearchData.filter((item) =>
        item.phoneNumber.includes(values.phoneNumber)
      );
    }
    // 根据日期范围筛选
    if (values.dateRange) {
      const [startDate, endDate] = values.dateRange;
      newsearchData = newsearchData.filter((item) => {
        const itemDate = new Date(item.date);
        return itemDate >= startDate && itemDate <= endDate;
      });
    }
    setsearchData(newsearchData);
  };
  // 导出excel表格功能
  // const handleExport = () => {
  //   // 定义表头映射
  //   const headerMap = columns.reduce((acc, col) => {
  //     acc[col.dataIndex] = col.title;
  //     return acc;
  //   }, {});
  //   // 生成表头数组
  //   const headers = Object.values(headerMap);
  //   // 转换数据格式，将数据中的键替换为中文表头对应的键
  //   const formattedData = searchData.map((item) => {
  //     const newItem = {};
  //     Object.keys(item).forEach((key) => {
  //       if (headerMap[key]) {
  //         newItem[headerMap[key]] = item[key];
  //       }
  //     });
  //     return newItem;
  //   });
  //   // 创建工作表
  //   const ws = XLSX.utils.json_to_sheet(formattedData, { header: headers });
  //   // 创建工作簿
  //   const wb = XLSX.utils.book_new();
  //   XLSX.utils.book_append_sheet(wb, ws, "果币充值");
  //   // 写入文件
  //   XLSX.writeFile(wb, "果币充值");
  // };
  const handleExport = () => {
    const ws = XLSX.utils.json_to_sheet(searchData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "果币充值");
    XLSX.writeFile(wb, "果币充值");
  };
  //modal
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // 新增加充值
  const FormonFinish = async (values) => {
    console.log("Success:", values);
    const res = await getadd(values);
    console.log(res, "新增");
    alert(res.data.message)
    getList()
  };

  return (
    <div>
      <p>果币</p>
      <Form
        form={form}
        style={{
          maxWidth: formLayout === "inline" ? "none" : 700,
        }}
        name="basic"
        layout={formLayout}
        onFinish={onFinish}
      >
        <Form.Item label="业务类型" name="businessType">
          <Select placeholder="请选择业务类型" style={{ width: "150px" }} allowClear>
            <Option value="充值">充值</Option>
            <Option value="订单消费">订单消费</Option>
            <Option value="退款">退款</Option>
          </Select>
        </Form.Item>
        <Form.Item
          label="店铺名称"
          name="shopName"
          style={{ margin: "0 80px" }}
        >
          <Input placeholder="请输入店铺名称" allowClear/>
        </Form.Item>
        <Form.Item label="手机号" name="phoneNumber">
          <Input placeholder="请输入手机号码" allowClear/>
        </Form.Item>
        <Form.Item
          label="日期查询"
          name="dateRange"
          style={{ marginTop: "10px" }}
        >
          <DatePicker.RangePicker />
        </Form.Item>
        <Form.Item
          style={{ display: "flex", marginTop: "10px", marginLeft: "80px" }}
        >
          <Button type="primary" htmlType="submit">
            查询
          </Button>
          <Button style={{ marginLeft: "10px" }} onClick={handleExport}>
            导出
          </Button>
        </Form.Item>
      </Form>
      <Button type="primary" onClick={showModal}>
        充值
      </Button>
      <Modal
        title="新增加充值"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
      >
        <Form
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          style={{
            maxWidth: 600,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={FormonFinish}
          autoComplete="off"
        >
          <Form.Item label="用户名" name="username">
            <Input allowClear placeholder="请输入用户名"/>
          </Form.Item>

          <Form.Item label="店铺名称" name="shopName">
            <Input allowClear placeholder="请输入店铺名称"/>
          </Form.Item>

          <Form.Item label="手机号码" name="phoneNumber">
            <Input allowClear placeholder="请输入手机号码"/>
          </Form.Item>

          <Form.Item label="业务单据" name="businessDocument" >
            <Input allowClear placeholder="请输入业务单据"/>
          </Form.Item>

          <Form.Item label="业务类型" name="businessType">
            <Select placeholder="请选择业务类型" allowClear>
              <Option value="订单消费">订单消费</Option>
              <Option value="退款">退款</Option>
              <Option value="充值">充值</Option>
            </Select>
          </Form.Item>

          <Form.Item label="流水类型" name="transactionType">
            <Select placeholder="请选择流水类型" allowClear>
              <Option value="收入">收入</Option>
              <Option value="支出">支出</Option>
            </Select>
          </Form.Item>

          <Form.Item label="时间" name="date">
            <Input allowClear placeholder="请输入时间"/>
          </Form.Item>

          <Form.Item label="果币" name="amount">
            <Input allowClear placeholder="请输入果币"/>
          </Form.Item>

          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              新增
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Table columns={columns} dataSource={searchData} />
    </div>
  );
}

export default MaterialDownload;
